package net.qqxh.webSocket.server;

import com.google.gson.Gson;
import net.qqxh.persistent.JfUserSimple;
import net.qqxh.service.FileService;

import net.qqxh.service.common.BaseCallBack;
import net.qqxh.service.task.FileResolveTaskCallBack;
import net.qqxh.webSocket.config.SpringWebSocketConfig;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author jason
 */
@ServerEndpoint(value = "/jfileSocketServer/{sid}", configurator = SpringWebSocketConfig.class)
@Component
public class JfileSocketServer {
    private final static Logger logger = LoggerFactory.getLogger(JfileSocketServer.class);

    private static int onlineCount = 0;
    private static boolean isWorking = false;
    private static CopyOnWriteArraySet<JfileSocketServer> webSocketSet = new CopyOnWriteArraySet<JfileSocketServer>();
    private Session session;
    private static FileService fileService;
    private String sid = "";
    @Autowired
    public void setFileService(FileService fileService) {
        JfileSocketServer.fileService = fileService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        this.sid = sid;
        if (isWorking) {
            return;
        }
        isWorking = true;
        final Gson gson = new Gson();
        JfUserSimple jfUserSimple = (JfUserSimple) session.getUserProperties().get("user");
        /*文件处理*/
        try {
            fileService.resolveAllFile(jfUserSimple.getSearchLib(), msg -> {
                try {
                    batchSend(gson.toJson(msg), null);
                    if (msg.getFinish()) {
                        isWorking = false;
                    }
                } catch (IOException e) {
                    isWorking = false;
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        //群发消息
        for (JfileSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (this.session) {
            if (this.session.isOpen()) {
                /*使用异步发送消息的方法*/
                this.session.getBasicRemote().sendText(message);
            } else {
                logger.info("链接已经关闭，后台静默执行;");
            }
        }

    }


    /**
     * 群发自定义消息
     */
    public static void batchSend(String message, @PathParam("sid") String sid) throws IOException {
        for (JfileSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if (sid == null) {
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        JfileSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        JfileSocketServer.onlineCount--;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}